JS30 Day 7 筆記


Posted by GL on 2023-05-23

目標

用 4 個範例來熟悉幾個常見的 array 操作

Demo

會使用到的資料

const people = [
  { name: 'Wes', year: 1988 },
  { name: 'Kait', year: 1986 },
  { name: 'Irv', year: 1970 },
  { name: 'Lux', year: 2015 }
];

const comments = [
  { text: 'Love this!', id: 523423 },
  { text: 'Super good', id: 823423 },
  { text: 'You are the best', id: 2039842 },
  { text: 'Ramen is my fav food ever', id: 123523 },
  { text: 'Nice Nice Nice!', id: 542328 }
];

題目

  1. At least one person 19 or older?

    題目: people 中是否有 19 歲以上的人?
    思路: 用 some() 方法,判斷 people array 中的每一筆資料,只要找到一筆符合條件,就回傳 true並結束,否則回傳 false

    const isAdult = people.some(person =>{
    // 現在的年份哦
        const currentYear = (new Date()).getFullYear()
    
        // 現在年份 - 此 person 的出生年份是否大於等於 19
        return currentYear - person.year >= 19
    })
    
    // 簡潔寫法
    // const isAdult = people.some(person => (new Date()).getFullYear() - person.year >= 19)
    
  1. Is everyone 19 or older?

    題目: people 陣列中的人是否都大於 19 歲?
    思路: 用 every() 方法,判斷 people array 中的每一筆資料,如果所有筆資料都符合條件,回傳 true ,否則只要有一筆不符合就回傳 false 並結束。

     const allAdults = people.every(person=>{
         const currentYear = (new Date()).getFullYear()
         return currentYear - person.year >= 19
     })
    
     // 簡潔寫法
     // const allAdults = people.every(person => new Date().getFullYear() - person.year >= 19)
    
  2. find the comment with the ID of 823423

    題目: 找到 ID 為 823423 的 comment
    思路: 用 find() 方法,會將 comments 中每一筆資料做判斷,返回第一筆符合條件的資料

     const comment = comments.find(item => item.id === 823423
     )
    
  3. Find the comment with this ID,delete the comment with the ID of 823423

    題目: 在 comments 中找到 id 是 823423 的資料索引值,並透過索引值刪除這筆資料
    思路: 用 findIndex()slice() 以及 ES6 的 Spread Syntax 的方法

```javascript=
const index = comments.findIndex(comment=>comment.id === 823423)
const newComment = [...comments.slice(0,index), ...comments.slice(index+1)]

// 先複製另一個 comments, 然後用 splice 的方法刪除 index (先複製原來的陣列,再另外修改,避免直接用 splice 動到原來的陣列資料)
const newComments = [...comments]
newComments.splice(index,1)
```

Javascript

splice() & slice()

  1. slice(startIndex, endIndex) : 回傳一個新陣列,為原陣列選擇之 start 至 end(不包含 end),原本的陣列不會被修改。

  2. splice(start, deleteCount, item) :會改變原始資料,從 array 中刪除特定的 element,往後刪除。若 deleteCount 個 element,deleteCount 為 0 時,添加新元素

// 複製新的物件
object.assign({},obj1)
JSON.parse(JSON.stringify(object))
// 小練習
let obj1 = { count: 1}
let obj2 = obj1
let obj3 = Object.assign({}, obj1)
obj1.count = 5
le obj4 = JSON.parse(JSON.srtringify(obj2))

console.log(obj1.count + obj2.count + obj3.count + obj4.count) //  16

參考資料:


#JS 30







Related Posts

新手必看 - 淺談 檔案格式

新手必看 - 淺談 檔案格式

【Day04】用 you-get 測試下載 Youtube 影片

【Day04】用 you-get 測試下載 Youtube 影片

[Linux] 使用 dd 指令測試 disk IO 效能

[Linux] 使用 dd 指令測試 disk IO 效能


Comments